import config from "config";
import React from "react";
import { message } from "antd";
import httpFetch from "share/httpFetch";
import errorMessage from "share/errorMessage";
import {
  loadScript,
  setLocalStorage,
  getQueryUrlParam,
  messages,
} from "share/common";
import { setAdminMode, setEnableScan } from "actions/main";
import baseService from "share/base.service";
import menuRoute from "routes/menuRoute";
import { setOrganization } from "actions/budget";
import { setCreditModel } from "actions/credit-setting";
import { setUserOrganization } from "actions/login";
import budgetOrganizationService from "containers/budget-setting/budget-organization/budget-organnization.service";
import creditModelService from "containers/credit-setting/credit-model/credit-model.service";
import mileageExpenseService from "containers/mileage-subsidy-expense/mileage-subsidy-expense.service";
import showMenu from "routes/showMenu";
import configureStore from "stores";
import keDaScanService from "components/keDaScanService";
import canonScanService from "components/canon-scan/canon-scan-service";

export default {
  //退出
  //TODO:增加逻辑判断用户是否要需要重新登录，后端给接口存储新手引导的flag
  //临时方法：把customTable和新手引导的localStorage暂存后再放进去
  loginOut: function () {
    return new Promise((resolve, reject) => {
      httpFetch
        .post(config.baseUrl + "/api/logout")
        .then((res) => {
          this.localStorageClearHly();
          window.sessionStorage.clear();
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },
  //清除数据 留下的必须的数据
  localStorageClearHly() {
    let storageArr = [
      "hly.guide",
      // "hly.tableConfig",
      "hly.menuConfig.tenantMode",
      "hly.menuConfig.companyMode",
      "hly.commonFunction",
      "hly.layout",
      "hly.executedOperation",
      "hly.travel.city.history",
      "localNeedProtocol",
    ];
    let storageMap = {};
    storageArr.map((item) => (storageMap[item] = localStorage.getItem(item)));
    window.localStorage.clear();
    storageArr.map(
      (item) => storageMap[item] && setLocalStorage(item, storageMap[item])
    );
  },
  //   调用{sso-service}/sso/logoutDecide?domainName=XXX，返回为clientName,
  //   如果为空直接清除token，否则清除token后调用第三方退出接口
  // {sso-service}/sso/centralLogout?clientName=XXX，
  // 根据返回的302进行重定向
  //判断是不是通过单点登录进来
  loginOutSso: function () {
    return new Promise((resolve, reject) => {
      //退出本系统
      this.loginOut()
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
      //还需要判断是否是通过父系统登录进来的，如果是，就会跳回父系统
      // httpFetch.get(config.ssoUrl + '/sso/logoutDecide?domainName=' + window.location.hostname)
      //   .then((res) => {
      //     let clientName = res.data;
      //     if (clientName) {
      //       //这是 /v1/login 单点登录方式
      //       // /v2/login 是需要在调 /v2/login 接口的时候记住 clientName
      //       this.loginOutSsoCentralLogout(clientName)
      //     }
      //   })
      //   .catch((err) => {
      //     // errorMessage(err.response);
      //   })
      //v2/login 属于另一种单点登录方式退出
      //企业单点登录，客户端名称需要记住，点击退出的时候
      let sso_clientName = window.sessionStorage.getItem("sso_clientName");
      let sso_loginType = window.sessionStorage.getItem("sso_loginType");
      if (sso_clientName && sso_loginType === "sso") {
        window.sessionStorage.setItem("sso_clientName", null);
        window.sessionStorage.setItem("sso_loginType", null);
        this.loginOutSsoCentralLogout(sso_clientName);
      }
    });
  },
  //退出单点登录中的父系统
  loginOutSsoCentralLogout: function (clientName) {
    //要先记着是不是企业登录过了的一个状态
    //clientName 为企业登录的时候，/v2/login 接口返回的数据
    let url = window.location.protocol + "//" + window.location.hostname;
    window.location.href =
      config.ssoUrl +
      "/sso/centralLogout?clientName=" +
      clientName +
      "&service=" +
      url;
  },

  //针对有参数的URL处理 by 洪阳林
  transRealUrl: function (item, cacheUrl, location, currentPage) {
    let url = item.url;

    /*start--替换URL--start--王若楠*/
    /*生成面包屑的时候直接用当前路径里的参数值替换掉要生成的这个面包屑的url里的类似:id的这种参数*/
    let oldUrlArr = currentPage[currentPage.length - 1].url.split("/");
    let newUrlPathArr = item.url.split("/");
    let oldUrlPathArr = location.pathname.split("/");
    newUrlPathArr.map((item) => {
      if (item.indexOf(":") !== -1) {
        oldUrlArr.map((old, oldIndex) => {
          if (old === item) {
            url = url.replace(item, oldUrlPathArr[oldIndex]);
          }
        });
      }
    });
    /*end--替换URL--end*/

    cacheUrl &&
      cacheUrl.length > 0 &&
      cacheUrl.map((i) => {
        if (i.key === item.key) {
          url = i.url;
        }
      });
    let backUrlKey = getQueryUrlParam("backUrlKey");
    if (backUrlKey && cacheUrl && cacheUrl.length > 0) {
      url = menuRoute.getRouteItem(backUrlKey, "key").url;
    }
    return url;
  },
  udeskSignature2: function (user, web_plugin_id) {
    return new Promise((resolve, reject) => {
      httpFetch
        .get(config.baseUrl + "/api/udesk/signature")
        .then((res) => {
          // 1，h5push，用于推送
          // 2，user_id，用于辅助组件
          // 3，web_token，取值逻辑变了
          // 4，web_plugin_id，通过打开会话的入口区别开来，如果是通过反馈打开会话的，传反馈插件的id
          let data = res.data;
          //需要传入给客服的信息
          let userName = user.fullName;
          let companyName = user.companyName;
          let departmentName = user.departmentName;
          let phone = user.mobile ? user.mobile : user.userOID;
          let email = user.email;
          let c_desc = "来自中控的用户";
          //62121 反馈接入的插件id
          //22949 正常点击客服插件id
          let url =
            "" +
            "https://huilianyi.udesk.cn/im_client/?" +
            "web_plugin_id=" +
            web_plugin_id +
            "&" +
            "c_desc=" +
            c_desc +
            "&" +
            "c_name=" +
            userName +
            "&" +
            "c_org=" +
            companyName +
            "&" +
            "c_cn_departmentName=" +
            departmentName +
            "&" +
            "c_phone=" +
            phone +
            "&" +
            "c_email=" +
            email +
            "&" +
            "c_cf_客户ID=" +
            user.id +
            "&" +
            "h5push=true&" +
            "nonce=" +
            data.nonce +
            "&" +
            "timestamp=" +
            data.timestamp +
            "&" +
            "web_token=" +
            data.web_token +
            "&" +
            "signature=" +
            data.signature;
          res.data._url = url;
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },

  //重构了，这是新的
  udeskSignature: function (user, web_plugin_id) {
    let params = {
      web_plugin_type: web_plugin_id,
      c_desc: "来自中控的用户",
      // agent_id: user.id,
      h5push: true,
    };
    return new Promise((resolve, reject) => {
      httpFetch
        .get(config.baseUrl + "/api/udesk/redirect", params)
        .then((res) => {
          res.data._url = res.data.redirectUri;
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },
  /**
   * created by zhangran
   * 检查url时设置当前url及redux的值
   * @param sections  当前url路径分割数组
   * @param index  需要检查的url在sections内的位数
   * @param value  需要填入url及redux内的值
   * @param actions  redux操作函数
   * @param string  url内非值时的默认字符串
   * @param backKey  如果redux为空且进入了原始url时返回的页面key
   * @param extraReplace 如果还有其他需要替换的，放入这里: { string: value }
   * 函数提取出去 setUrl checkParams
   */
  setUrl: function (
    sections,
    index,
    value,
    actions,
    string,
    backKey,
    extraReplace = {},
    router,
    mainSelf
  ) {
    if (sections[index] === string) {
      if (value) {
        let url = sections.join("/").replace(string, value);
        Object.keys(extraReplace).map((key) => {
          url = url.replace(key, extraReplace[key]);
        });
        router.replace(url);
      } else {
        router.replace(menuRoute.getRouteItem(backKey, "key").url);
      }
      mainSelf.setState({ check: true });
    } else {
      actions(sections[index]);
    }
  },

  //菜单是否在菜单权限列表里面
  menuIsInPermissonMenuList(menu, menuList) {
    if (menuList.length) {
      let key = menu.key;
      
      for (let i = 0, len = menuList.length; i < len; i++) {
        let item = menuList[i];
        if (item.children) {
          if (this.menuIsInPermissonMenuList(menu, Object.values(item.children))) {
            return true
          }
        }
        if (item.subMenu) {
          if (this.menuIsInPermissonMenuList(menu, item.subMenu)) {
            return true
          }
        }

        if (item.key === key) {
          return true;
        }
      }
      return false;
    } else {
      return false;
    }
  },
  /**
   * created by zhangran
   * 参数检查方法，检查Url内是否含有需要保存在redux内的值，如果存在则根据url内参数进行对应的操作
   * 这样可以在进入一些特定url时自动检查状态从而更新redux
   * 函数提取出去 setUrl checkParams
   */
  checkParams: function (mainSelf) {
    const { adminMode, loginUser } = mainSelf.props;
    const supportBrowserHistory = typeof history.pushState !== "undefined";
    let nowPath = supportBrowserHistory ? location.pathname : location.hash;
    if (nowPath.indexOf("?") > -1) {
      nowPath = nowPath.substr(0, nowPath.indexOf("?"));
    }
    let nowCurrent = [];
    let nowSections = nowPath.split("/");
    nowSections.splice(0, 1);
    nowSections.map((section) => {
      let routeItem = menuRoute.getRouteItem(section, "key");
      routeItem !== null && nowCurrent.push(routeItem);
    });
    let noPermissionError = {
      title: messages("dashboard.key89" /*出错啦*/), //出错啦
      text: messages(
        "dashboard.key90" /*您无权限访问本页面*/
      ) /*'您无权限访问本页面'*/,
      buttonText: "",
      hasButton: false,
    };
    if (loginUser.enableNewPermission) {
      let menu = nowCurrent[0].subMenu ? nowCurrent[1] : nowCurrent[0];
      //企业滴滴账期
      // if(!menu){
      //   menu = nowCurrent[0].subMenu ? nowCurrent[0] : nowCurrent[0];
      // }
      let menuList = mainSelf.state.menu;
      let userPermissionAllMenus = mainSelf.state.userPermissionAllMenus;
      let arr = userPermissionAllMenus.filter((item) => item.key === menu.key);
      if (menu.key === "personal-settings" && adminMode) {
        mainSelf.props.dispatch(setAdminMode(false));
        //个人设置 跨模式跳转，单独设置
        baseService.getInfo().then(() => {
          mainSelf.menuRouterDeal(
            menuRoute.getMenuItemByAttr("personal-settings", "key").url
          );
        });
      }
      if (
        this.menuIsInPermissonMenuList(menu, menuList) ||
        (arr && arr.length)
      ) {
        this.checkSpecialRouter(mainSelf);
      } else {
        //如果访问的菜单是该用户不拥有的菜单
        this.setErrorContent(mainSelf, noPermissionError);
        return;
      }
      return;
    }
  },

  checkSpecialRouter: function (mainSelf) {
    const {
      loginUser,
      user,
      organization,
      creditModel,
      company,
    } = mainSelf.props;
    let commonErrorContent = messages("common.error");
    let errorContent = null;
    //如果访问的菜单是如下特殊菜单
    let path =
      typeof history.pushState !== "undefined"
        ? location.pathname
        : location.hash;
    if (path.indexOf("?") > -1) {
      path = path.substr(0, path.indexOf("?"));
    }
    let section = path.split("/");
    if (
      !(
        ~path.indexOf("/new-expense-report/") ||
        ~path.indexOf("/expense-report-detail/")
      )
    ) {
      if (loginUser.userOID && loginUser.userOID !== user.userOID) {
        baseService.changeLoginInfo(loginUser.userOID);
      }
    }
    mainSelf.setState({ check: false });
    if (
      path.indexOf("budget-organization-detail") > -1 &&
      organization.id !== section[5]
    ) {
      //预算组织内部页面的组织id检查
      let actions = (value) => {
        budgetOrganizationService
          .getOrganizationById(value)
          .then((res) => {
            mainSelf.props.dispatch(setOrganization(res.data));
            this.setNoError(mainSelf);
          })
          .catch((e) => {
            message.error(commonErrorContent);
            this.setNoError(mainSelf);
          });
      };
      this.setUrl(
        section,
        5,
        organization.id,
        actions,
        ":id",
        "budget-organization"
      );
    } else if (
      path.indexOf("credit-model-detail") > -1 &&
      creditModel.id !== section[5]
    ) {
      //信用设置内部信用模型id检查
      let actions = (value) => {
        creditModelService
          .getCreditModel(value)
          .then((res) => {
            mainSelf.props.dispatch(setCreditModel(res.data));
            this.setNoError(mainSelf);
          })
          .catch((e) => {
            message.error(commonErrorContent);
            this.setNoError(mainSelf);
          });
      };
      this.setUrl(section, 5, creditModel.id, actions, ":id", "credit-model");
    } else if (path.indexOf("/budget/") > -1) {
      //预算组织的默认检查
      let budgetErrorContent = {
        text: messages("dashboard.key92" /*该账套下的默认预算组织未启用*/),
        title: messages("dashboard.key93" /*预算组织不可用*/),
        skip: menuRoute.getRouteItem("budget-organization").url,
        buttonText: messages("dashboard.key94" /*去设置*/),
        hasButton: mainSelf.checkAuthorities("ROLE_TENANT_ADMIN"),
      };
      budgetOrganizationService
        .getOrganizationBySetOfBooksId(company.setOfBooksId)
        .then((response) => {
          if (response.data.isEnabled) {
            mainSelf.props.userOrganization.id !== response.data.id &&
              mainSelf.props.dispatch(setUserOrganization(response.data));
            this.setNoError(mainSelf);
          } else {
            this.setErrorContent(mainSelf, budgetErrorContent);
          }
        })
        .catch((e) => {
          let content =
            e.response && e.response.data
              ? e.response.data.message
                ? e.response.data.message
                : commonErrorContent
              : commonErrorContent;
          mainSelf.props.dispatch(setUserOrganization({ message: content }));
          budgetErrorContent.text = content;
          this.setErrorContent(mainSelf, budgetErrorContent);
        });
    } else if (path.indexOf("/mileage-subsidy-expense") > -1) {
      mileageExpenseService
        .isHaveRule()
        .then((res) => {
          this.setNoError(mainSelf);
        })
        .catch((err) => {
          if (
            err.response.data.responseCode === "4001" ||
            err.response.data.errorCode === "4001"
          ) {
            errorContent = {
              text: `${messages(
                "dashboard.key91" /*请重试操作或联系管理员:(*/
              )}：${user.fullName} ${user.mobile}`,
              title: messages("dashboard.key96" /*未设置每公里单价*/),
            };
            this.setErrorContent(mainSelf, errorContent);
          }
        });
    } else {
      mainSelf.setState({
        check: true,
        error: false,
        errorContent: {},
      });
    }
  },

  setNoError: function (mainSelf) {
    mainSelf.setState({
      check: true,
      error: false,
      errorContent: {},
    });
  },

  setErrorContent: function (mainSelf, errorContent) {
    mainSelf.setState(
      {
        check: true,
        error: true,
        errorContent,
      },
      () => {
        menuRoute.updateCurrentPageFun();
      }
    );
  },
  /**
   * 检查菜单的显示与隐藏
   * @param menuItem   菜单对象
   * @param adminMode  是否是管理员模式
   * @param tenantMode 是否是集团模式
   * @param isOldCompany 是否是老公司
   * @returns {boolean|*}
   */
  checkMenuAuth: function (menuItem, adminMode, tenantMode, isOldCompany) {
    const log = (key) => (value) => {
      if (menuItem.key === key) {
        console.log(key, value)
      }
    }
    if (!menuItem) {
      return false;
    }
    let loginUser = configureStore.store.getState().login.loginUser;
    //必须启用新权限情况才显示
    let showInNewPermission = menuItem.newPermission
      ? loginUser.enableNewPermission
      : true;
    //判断是否有子菜单
    let hasChild = false;
    //如果有subMenu，则判断子菜单是否有显示的
    if (menuItem.subMenu) {
      menuItem.subMenu.map((subMenu) => {
        hasChild =
          hasChild ||
          this.checkMenuAuth(subMenu, adminMode, tenantMode, isOldCompany);
      });
    } else {
      //如果没有subMenu，则显示
      hasChild = true;
    }
    let oldPermission = true;
    let newPermission = true;
    if (!loginUser.enableNewPermission) {
      oldPermission = this.oldPermissionCheckMenu(
        menuItem,
        adminMode,
        tenantMode,
        isOldCompany
      );
    } else {
      //判断员工,管理员,集团,公司模式下的隐藏与显示
      newPermission = this.shouldShowInCurrentMode(
        menuItem,
        adminMode,
        tenantMode
      );
    }
    let commonPermission = showInNewPermission && hasChild;
    log('union2')({
      commonPermission,
      showInNewPermission,
      hasChild,
      oldPermission,
      "loginUser.enableNewPermission": loginUser.enableNewPermission,
      'menuItem.menuShowAttr': menuItem.menuShowAttr,
      adminMode,
      tenantMode,
      newPermission
    })

    return commonPermission && oldPermission && newPermission;
  },

  //根据每个菜单具有的显示属性，判断其在当前模式下是否应该展示
  shouldShowInCurrentMode: function (menuItem, adminMode, tenantMode) {
    let showAdmin = adminMode ? "admin" : "employee";
    let showTenant = tenantMode ? "tenant" : "company";
    let show =
      menuItem.menuShowAttr &&
      menuItem.menuShowAttr.some((item) => item[showAdmin] && item[showTenant]);
    return show;
  },

  //老权限时检测一个菜单是否应该被放出。其实现在已经没有老权限了，只是还在保留
  oldPermissionCheckMenu: function (
    menuItem,
    adminMode,
    tenantMode,
    isOldCompany
  ) {
    let oldPermission = true;
    //判断管理员模式与非管理员模式下的隐藏与显示
    let showInAdmin =
      (adminMode && menuItem.admin) ||
      (!adminMode && !menuItem.admin) ||
      (menuItem.parent && menuRoute.getRouteItem(menuItem.parent).admin);
    //判断集团模式下的隐藏与显示
    let showInTenant = tenantMode && menuItem.tenant;
    //判断公司模式下的隐藏与显示
    let showInCompany = !tenantMode && menuItem.company;
    //判断公司、集团模式下都显示
    let showInBoth = !menuItem.company && !menuItem.tenant;
    let routeIsShow = configureStore.store.getState().main.routeIsShow;
    //是否路由放出
    let showInRoute =
      !routeIsShow.hasOwnProperty(menuItem.key) || routeIsShow[menuItem.key];
    //判断角色控制的隐藏与显示
    let showInRole =
      !menuItem.role ||
      React.Component.prototype.checkAuthorities(menuItem.role);
    //页面角色权限隐藏与显示
    let showPageInRole =
      !menuItem.pageRole ||
      React.Component.prototype.checkPageRole(menuItem.pageRole);
    //判断任一角色控制的隐藏与显示
    let showInHasRole =
      !menuItem.hasRole ||
      React.Component.prototype.hasAnyAuthorities(menuItem.hasRole);
    //判断functionProfile的隐藏与显示
    let showInFunctionProfile =
      !menuItem.fpItem ||
      React.Component.prototype.checkFunctionProfiles(
        menuItem.fpItem,
        menuItem.fpValue,
        false
      );
    //是否配置放出
    let hasConfig = showMenu.isContained(menuItem.key);
    //判断老公司下是否显示
    let showInOldCompany =
      !menuItem.oldCompany ||
      (menuItem.oldCompany === "OLD_ONLY" && isOldCompany) ||
      (menuItem.oldCompany === "NEW_ONLY" && !isOldCompany);
    //是否域名隐藏
    let hideInUrl = function () {
      if (!menuItem.hideInUrl) return false;
      if (typeof menuItem.hideInUrl === "string")
        return location.host.indexOf(menuItem.hideInUrl) > -1;
      else {
        let isHide = false;
        menuItem.hideInUrl.forEach((url) => {
          if (location.host.indexOf(url) > -1) isHide = true;
        });
        return isHide;
      }
    };
    oldPermission =
      showInRoute &&
      showInRole &&
      showPageInRole &&
      showInHasRole &&
      showInFunctionProfile &&
      hasConfig &&
      showInOldCompany &&
      showInAdmin &&
      (showInTenant || showInCompany || showInBoth) &&
      !hideInUrl();
    return oldPermission;
  },

  /*
   * 获取公司列表
   * bug 36669
   * 新注册的公司只有一个公司，进入公司维护页面每次新增这个公司，需要更新这个值
   * */
  getAvailableCompany: function (extraParam = {}) {
    let params = {
      enabled: "true",
    };
    return new Promise((resolve, reject) => {
      httpFetch
        .get(`${config.baseUrl}/api/company/available`, {
          ...params,
          ...extraParam,
        })
        .then((response) => {
          resolve(response);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },

  changeCompany: function (companyId) {
    return httpFetch.post(`${config.baseUrl}/api/company/change/${companyId}`);
  },

  checkEnable: function () {
    console.log("是不是走到了判定CANON_V2", configureStore.store.getState().main.enableScan)
    return configureStore.store.getState().main.enableScan === "CANON_V2";
  },

  // 佳能扫描仪检测
  checkCanonScan: function (dispatch) {
    const staticUrl = "https://misc.huilianyi.com/heliosweb";
    Promise.all([
      loadScript(`${staticUrl}/canon-scanner/jquery-3.2.1.min.js`),
      loadScript(`${staticUrl}/canon-scanner/es6-promise.min.js`),
    ])
      .then(() => {
        loadScript(`${staticUrl}/canon-scanner/scan.js`).then(() => {
          // 通过加载js得到imageFORMULAScanJS
          // eslint-disable-next-line no-undef
          imageFORMULAScanJS
            // eslint-disable-next-line no-undef
            .getScannerList(imageFORMULAScanJS.DEFAULT.FQDN)
            .then(() => {
              if (!this.checkEnable()) {
                dispatch(setEnableScan("CANON"));
              }
            })
            .catch(() => {
              if (!this.checkEnable()) {
                dispatch(setEnableScan("UNSUPPORT"));
                this.checkScanSnap(dispatch);
              }
            });
        });
      })
      .catch(() => {
        if (!this.checkEnable()) {
          dispatch(setEnableScan("UNSUPPORT"));
          this.checkScanSnap(dispatch);
        }
      });
  },

  // 新版佳能卷票机检测 需要检测通过
  checkCanonScanV2: function (dispatch) {
    let timer = null;
    let uniqueKey = null;
    let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    let isIE =
      userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    let isIE11 =
      userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (!isIE && !isIE11) {
      const connector = canonScanService.initWebSocket({
        onOpen: () => {
          const params = {
            command: "CONNECT",
          };
          if (uniqueKey) {
            params.uniqueKey = uniqueKey;
          }
          const dataSend = `${JSON.stringify(params)}\0`;
          connector.send(dataSend);
        },
        onMessage: (res) => {
          const result = JSON.parse(res.data.replace("\0", ""));
          if (result.msgType === "CONNECT") {
            if (uniqueKey) {
              return !1;
            }
            uniqueKey = result.uniqueKey;
            try {
              canonScanService.startScan({
                key: result.uniqueKey,
                authorization: `Bearer ${
                  configureStore.store.getState().main.authToken.access_token
                }`,
              });
              timer = setTimeout(() => {
                this.checkCanonScan(dispatch);
              }, 5000);
              setTimeout(() => {
                connector.close();
              }, 30000);
            } catch (e) {
              connector.close();
              this.checkCanonScan(dispatch);
            }
          } else if (result.msgType === "init") {
            timer && clearTimeout(timer);
            if (result.msgContent === "true") {
              dispatch(setEnableScan("CANON_V2"));
            } else {
              this.checkCanonScan(dispatch);
            }
            connector.close();
          }
        },
        onerror: () => {
          connector.close();
          timer && clearTimeout(timer);
          this.checkCanonScan(dispatch);
        },
      });
    } else {
      this.checkCanonScan(dispatch);
    }
  },

  // 公版
  //```mermaid
  // graph TD
  // IE11(是否是IE11)
  // 服务端ws(和服务端建立ws连接)
  // 富士通(连接富士通)
  // 柯达(尝试连接柯达)
  // 开始扫描(fa:fa-star 开始扫描)

  // 检查扫描仪 --> IE11
  // IE11 -->|否| 服务端ws
  // IE11 -->|是| 富士通
  // 服务端ws --> |连接成功| 开始扫描
  // 开始扫描
  // 服务端ws --> |连接失败或超时 | 富士通
  // 富士通  --> |成功| 开始扫描
  // 富士通 --> |失败| 柯达

  // 麦当劳版本
  //```mermaid
  // graph TD
  // 富士通(连接富士通)
  // 开始扫描(fa:fa-star 开始扫描)
  // 富士通  --> |成功| 开始扫描
  // 富士通 --> |失败| 错误信息

  //检查扫描仪支持
  checkScan: function (dispatch) {
    // this.checkCanonScanV2(dispatch);
    if (window.location.hostname === "localhost") {
      dispatch(setEnableScan("MOCK"));
    } else {
      console.log('是不是走到了checkScan-checkScanSnap这步')
      this.checkScanSnap(dispatch);
    }
  },
  checkScanSnap(dispatch) {
    const staticUrl = "https://misc.huilianyi.com/heliosweb";
    httpFetch
      .get("http://localhost:8089/signalr/hubs")
      .then(() => {
        loadScript(`${staticUrl}/scaner/jquery-1.6.4.js`).then(() => {
          loadScript(`${staticUrl}/scaner/jquery.signalR-2.2.3.min.js`).then(
            () => {
              Promise.all([
                loadScript("http://localhost:8089/signalr/hubs"),
                loadScript(`${staticUrl}/scaner/fujitsu.scansnap.initiate.js`),
              ]).then(() => {
                console.log('是不是走到了localhost:8089这布')
                if (!this.checkEnable()) {
                  console.log('是不是走到了设置SCAN_SNAP 这步')
                  dispatch(setEnableScan("SCAN_SNAP"));
                }
              });
            }
          );
        });
      })
      .catch((e) => {
        console.warn("未检测到富士通扫描仪");
        return;
        if (!this.checkEnable()) {
          this.checkKeDaScan(dispatch);
        }
      });
  },

  //查找并返回接收到的菜单数组的第一个菜单
  lookForFirstMenu: function (menu, adminMode, tenantMode, isOldCompany) {
    let newPermissionSortedMenus = configureStore.store.getState().login
      .newPermissionSortedMenus;
    let checkMenuAuthParams = [adminMode, tenantMode, isOldCompany];
    let len = menu.length;
    for (let i = 0; i < len; i++) {
      if (menu[i].subMenu) {
        let res = this.lookForFirstMenu(
          menu[i].subMenu,
          ...checkMenuAuthParams
        );
        if (res) {
          return res;
        }
      } else {
        let bool = this.checkMenuAuth(menu[i], ...checkMenuAuthParams);
        if (bool) {
          if (menu[i].parent) {
            let boo2 = false;
            //要确保这个可以展示的菜单其父菜单也可以展示
            let parent = newPermissionSortedMenus.filter(
              (item) => item.key === menu[i].parent
            );
            if (parent && parent.length) {
              boo2 = this.checkMenuAuth(parent[0], ...checkMenuAuthParams);
            }
            if (bool && boo2) {
              return menu[i];
            }
          } else {
            return menu[i];
          }
        }
      }
    }
  },
};
